import React,{Component} from 'react';
import { Icon, Input, Button, Table, Pagination, Modal, Radio, Form, message, Tabs } from 'antd';
import { Link } from 'react-router-dom';
import './index.less';
import axios from 'axios';
import copy from 'copy-to-clipboard';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
import Bread from '../../common/Bread/index';

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'


const Search = Input.Search;
class UserList extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			visible: false,
			visibleRefuse: false,
			visibility: false,
			visibleRefuseApply: false,
			page:['1','10','20','30','40','50','60','70','80','90'],
			data:[],
			code: '',
			orgId: 1,
			value: 1,
			link: 'http://106.37.72.95:9080/#/Net/ApprovalRecord',
			page_1: 1,
			page_2: 1,
			limit: 10,
			limit_1: 10,
			searchValue: '',
			key: 1,
		}
	}
	componentWillMount(){
		this.userListFn(this.state.page_1,this.state.limit);
	}
	userListColums = [{
		title: '组织名称',
		dataIndex: '组织名称',
		key: '组织名称',
	  },{
		title: '姓名',
		dataIndex: '姓名',
		key: '姓名',
	  },{
		title: '手机',
		dataIndex: '手机',
		key: '手机',
	  },{
		title: '加入时间',
		dataIndex: '加入时间',
		key: '加入时间',
	  }, 
	 //  {
		// title: '操作',
		// key: '操作',
		// render: (text) => (
		// 	<span>
		// 		<span className="deleteIcon" onClick={this.handleDelete.bind(this,text)}>
		// 			<img src={require('./img/delete_icon.png')} />
		// 		</span>
		// 	</span>
		// )
	 // }
	 ];
	 
	 userJoinColums = [{
		title: 'id',
		dataIndex: 'id',
		key: 'id',
	  },{
		title: '姓名',
		dataIndex: 'name',
		key: '姓名',
	  }, {
		title: '手机',
		dataIndex: 'telPhone',
		key: '手机',
	  }, {
		title: '申请加入时间',
		dataIndex: 'crtTime',
		key: '申请加入时间',
		width: 300
	  }, {
		title: '申请理由',
		dataIndex: 'reason',
		key: '申请理由',
		
	  },{
		title: '状态',
		dataIndex: 'status',
		key: '状态',
		
	  },  {
		title: '操作',
		key: '操作',
		render: (text,record) => (
				<div>
					<span className={text['status'] !=='审核中' ? 'btnColor disableColor' : 'btnColor'} onClick={this.handleComfirm.bind(this,text)} style={{marginRight: 10}}>通过</span>
					<span className={text['status'] !=='审核中' ? 'btnColor disableColor' : 'btnColor'} onClick={this.handleRefuse.bind(this,text)}>拒绝</span>
				</div>
		)
	 }];
	//邀请码弹窗
	handleOk = () => {
        this.setState({ 
        	visibility: false,
        });
    
    }
	//此处做通过弹窗确定后数据更新接口
    handleOkConfirm = () => {
    	const id = this.state.rowId;
    	this.commonFn(id,1);
    	this.setState({
        	visible: false,
        });
    }
    //此处做拒绝弹窗确定后数据更新接口
    handleOkRefuse = () => {
        const id = this.state.rowId;
    	this.commonFn(id,'-1');
        this.setState({
        	visibleRefuse: false,
        });
    }

    commonFn= (id,status)=> {
    	const _this = this;
    	const data = {
    		id: id,
    		status: status
    	}
    	const Token = localStorage.getItem("token");
    	axios({
    		method: 'post',
    		url: '/api/customer/user/approval/verify',
    		data: data,
    		headers: {
    			'Content-Type': 'application/json',
				Authorization:Token,
    		}
    	})
    	.then(function(response){
    		if(response.data.code == 201){
    			message.warning('重复加入');
    		}else if(response.data.code == 202){
    			message.warning('没有申请记录');
    		}else if(response.data.code == 203){
    			message.warning('已审核');
    		}else if(response.data.code == 200){
    			message.success('操作成功');
    			setTimeout(function(){
	        		_this.userJoinApply(_this.state.page_2,_this.state.limit_1);
	        	},1000);
    		}
       		// console.log(response)
    	})
    	.catch(function(error){
    		console.log(error)
    	})
    }
    handleCancel = () => {
        this.setState({ 
        	visible: false,
        	visibleRefuse: false, 
			visibility: false,
			visibleRefuseApply: false,
        });
    }
    handleDelete = (text)=>{
    	this.setState({
            // visible: true,
        });
    }

    handleComfirm = (text)=>{
    	//此处填写申请通过交互
    	if(text['status'] !== '审核中'){
    		return 
    	}else{
    		this.setState({
	    		visible: true,
	    		rowId: text['id'],
    		})
    	}
    }
    handleRefuse = (text)=>{
    	//此处填写申请拒绝交互
    	if(text['status'] !== '审核中'){
    		return
    	}else {
    		this.setState({
	    		visibleRefuseApply: true,
	    		rowId: text['id'],
    		})
    	}
    }
    handleOkRefuseApply = ()=>{
    	this.setState({
    		visibleRefuseApply: false,
    		visibleRefuse: true
		})
    }
    
	onShowSizeChange = (current, pageSize)=> {
		// console.log(current, pageSize);
		this.setState({
			limit: pageSize,
		})
		this.userListFn(current,pageSize);
		this.searchUserList(current,pageSize);
	}
	onChange = (pageNumber)=> {
		// console.log('Page: ', pageNumber);
		this.setState({
			page_1: pageNumber,
		})
		this.userListFn(pageNumber);
		this.searchUserList(pageNumber);
	}

	onShowSizeChange_1 = (current, pageSize)=> {
		// console.log(current, pageSize);
		this.setState({
			limit_1: pageSize,
		})
		this.userJoinApply(current,pageSize);
		this.searchApply(current,pageSize);
	}
	onChange_1 = (pageNumber)=> {
		// console.log('Page: ', pageNumber);
		this.setState({
			page_2: pageNumber
		})
		this.userJoinApply(pageNumber);
		this.searchApply(pageNumber);
	}
	
	onChangeRadio = (e) => {
	    // console.log('radio checked', e.target.value);
	    this.setState({
	      value: e.target.value,
	      code: ''
	    });
	  }
	//用户列表
	userListFn= (page_1,limit=this.state.limit)=>{
		const _this = this;
		const Token = localStorage.getItem("token");
		axios({
			method: 'get',
			url: '/api/customer/baasorg/org/userorg',
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			},
			params: {
				page: page_1,
				limit: limit
			}
		})
		.then(function (response) {
			let data = [];
			let orgId = 1;
			response.data&&response.data.data&&response.data.data.rows&&response.data.data.rows.forEach((e,i)=>{
				data.push({
					key: i+'',
					"组织名称": e.orgName,
					"姓名": e.name,
					"手机": e.telPhone,
					"加入时间": e.createTime,
				})
			})
			orgId = (response.data.data.total == 0) ? 'null' : response.data.data.rows[0].org_id;
			_this.setState({
				data: data,
				orgId: orgId,
				totalnum: response.data.data.total,
			})
			// console.log(response);
			
		})
		.catch(function (error) {
			console.log(error)
		});
		
	}	
	//用户加入申请
	userJoinApply = (page_2,limit_1=this.state.limit_1)=>{
    	//此处填写用户加入申请列表数据接口
    	this.userApplyFn('/api/customer/user/approval/applyListbyName?name=', page_2, limit_1)
    }
	//获取邀请码
	getCode= ()=>{
		const _this = this;
		const id = this.state.orgId;
		const Token = localStorage.getItem("token");
		axios({
			method: 'get',
			url: '/api/customer/baasorg/front/query/code?id='+id,
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
		})
		.then(function (response) {
			if(response.data.rel == false){
				message.error('未创建组织');
			}else if(response.data.rel == true){
				_this.setState({
			        visibility: true,
			        code: response.data.data
			    });
			}
			// console.log(response);
		})
		.catch(function (error) {
			message.error('请求失败，请刷新重试。')
		});
		
	}
	//重新生成邀请码
	InviteCode =()=>{
		const _this = this;
		const id = this.state.orgId;
		const Token = localStorage.getItem("token");
		axios({
			method: 'get',
			url: '/api/customer/baasorg/front/refresh/code?id='+id,
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			}
		})
		.then(function (response) {
			_this.setState({
				code: response.data.data
			})
			// console.log(response);
		})
		.catch(function (error) {
			message.error('请求失败，请刷新重试。')
		});
	}	
	//复制邀请码
	copyCode =()=>{
		copy(this.state.code);
    	message.success('复制成功，如果失败，请在输入框内手动复制.');
	}
	//复制邀请码
	copyLink =()=>{
		copy(this.state.link);
    	message.success('复制成功，如果失败，请在输入框内手动复制.');
	}

	callback=(key)=> {
	  // console.log(key);
	  this.setState({
	  	key: key
	  })
	  if(key == 1){
	  	this.userListFn(this.state.page_1,this.state.limit);
	  }else {
	  	this.userJoinApply(this.state.page_2,this.state.limit_1);
	  }
	}

	onSearch =(e)=>{
		e.persist();
		this.setState({
			searchValue: e.target.value
		})
		// const _this = this;
		// if(this.state.key == 1){
		// 	setTimeout(()=>{
		// 		if(this.state.searchValue == ''){
		// 			_this.userListFn(this.state.page_1,this.state.limit);
		// 		}else{
		// 			_this.searchUserList(this.state.page_1,this.state.limit);
		// 		}
		// 	})
		// }else {
		// 	setTimeout(()=>{
		// 		if(this.state.searchValue == ''){
		// 			_this.userJoinApply(this.state.page_2,this.state.limit_1);
		// 		}else {
		// 			_this.searchApply(this.state.page_2,this.state.limit_1);
		// 		}
		// 	})
		// }
	}
	//用户列表搜索
	searchUserList =(page_1,limit= this.state.limit)=>{
		const name = this.state.searchValue;
		const Token = localStorage.getItem("token");
		const _this = this;
		axios({
			method: 'get',
			url: '/api/customer/baasorg/queryOrgName?name='+ name,
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			},
			params: {
				page: page_1,
				limit: limit
			}
		})
		.then(function(response){
			let data = [];
			response.data&&response.data.data&&response.data.data.rows&&response.data.data.rows.forEach((e,i)=>{
				data.push({
					key: i+'',
					"组织名称": e.orgName,
					"姓名": e.name,
					"手机": e.tel_phone,
					"加入时间": e.create_time,
				});
				_this.setState({
					data: data,
					totalnum: response.data.data.total,
				})
			})
			// console.log(response)
		})
	}

	//用户加入申请搜索
	searchApply =(page_2,limit_1=this.state.limit_1)=>{
		const name = this.state.searchValue;
		this.userApplyFn('/api/customer/user/approval/applyListbyName?name='+ name, page_2, limit_1)
	}
	enterSearch =(e)=>{
		e.persist();
		if(this.state.searchValue == ''){
			message.warning('请输入用户姓名');
		}else{
			if(this.state.key == 1){
				this.searchUserList(this.state.page_1,this.state.limit);
			}else {
				this.searchApply(this.state.page_2,this.state.limit_1);
			}
		}
	}

	userApplyFn =(url,page_2,limit_1)=>{
		const Token = localStorage.getItem("token");
		const _this = this;
		axios({
			method: 'get',
			url: url,
			headers: {
				'Content-Type': 'application/json',
				Authorization:Token,
			},
			params: {
				page: page_2,
				limit: limit_1
			}
		})
		.then(function(response){
			// console.log(response)
			let data=[];
			response.data&&response.data.data&&response.data.data.rows&&response.data.data.rows.forEach((e,i)=>{
				if(e.status == '0'){
					e.status = '审核中';
				}else if(e.status == '1'){
					e.status = '通过';
				}else if(e.status == '-1'){
					e.status = '拒绝';
				}
				data.push({
					key: i+'',
					"id": e.id,
					"name": e.name,
					"telPhone": e.telPhone,
					"crtTime": e.crtTime,
					"reason": e.reason,
					"status": e.status,
				})
			})
    		_this.setState({
    			data: data,
    			totalnum:response.data.data.total,
    		})
    		// console.log(response)
		})
		.catch(function (error) {
			message.error('请求失败，请刷新重试。')
		});
	}

	render() {
		const { visible,visibleRefuse, visibleRefuseApply, visibility } = this.state;
		const disabled = (this.state.value === 2) ? 'disabled': '';
		return (
			<div>
				<Bread bread={['组织管理',['组织管理','accountService'],['管理我创建的组织','accountService/UserList']]}/>
				<div className="manageOrg">
					<div className="tabBox_1">
						<div className="inviteUserBox">
							<Input type="text" placeholder="请输入用户姓名" className="input" onChange = {this.onSearch} />
							<Button type="primary" className="search" onClick={this.enterSearch}><img src={require('./img/search_icon.png')} /></Button>
							<Button type="primary" className="inviteBtn" onClick={this.getCode}>邀请用户</Button>
						</div>
						<Tabs defaultActiveKey="1" onChange={this.callback}>
					    <TabPane tab="用户列表" key="1">
					    	<div>
					    		<Table
					    			columns={this.userListColums} 
					    			dataSource={this.state.data} 
					    			bordered
					    			pagination={false} />
					    		<div className="page_foot">
					    			<span className="data_num">共{this.state.totalnum}条</span>
					    			<Pagination 
					    				pageSizeOptions={this.state.page} 
					    				className="page" 
					    				showSizeChanger 
					    				showQuickJumper
					    				onShowSizeChange={this.onShowSizeChange} 
					    				defaultCurrent={1} 
					    				total={this.state.totalnum} 
					    				onChange={this.onChange} />
					    		</div>
					    	</div>
					    </TabPane>
					    <TabPane tab="用户加入申请" key="2">
					    	<div>
					    		<Table
					    			className="tableFirst"
					    			columns={this.userJoinColums} 
					    			dataSource={this.state.data} 
					    			bordered
					    			pagination={false} />
					    		<div className="page_foot">
					    			<span className="data_num">共{this.state.totalnum}条</span>
					    			<Pagination 
					    				pageSizeOptions={this.state.page} 
					    				className="page" 
					    				showSizeChanger 
					    				showQuickJumper
					    				onShowSizeChange={this.onShowSizeChange_1} 
					    				defaultCurrent={1} 
					    				total={this.state.totalnum} 
					    				onChange={this.onChange_1} />
					    		</div>
					    	</div>
					    </TabPane>
					  </Tabs>
					</div>
					
					<Modal
					  visible={visible}
					  title="提示"
					  iconType="warning"
					  onCancel={this.handleCancel}
					  footer={[
					    <Button key="back" onClick={this.handleCancel}>取消</Button>,
					    <Button key="submit" type="primary" onClick={this.handleOkConfirm}>
					      确定
					    </Button>,
					  ]}
					>
					  <p className="textAlign">
					  		<b>通过申请</b>
					  		<span>您已经通过该用户的加入组织申请，该用户已经成为您组织的使用者。您可以在相应组织的“组织管理”中查询并管理该用户的相关信息。</span>
						  {/*<span className="CommonTips">您是否确认通过</span>
						  <span className="userName"> {this.state.userName} 的申请</span>*/}
					  </p>
					</Modal>
					<Modal
					  visible={visibleRefuseApply}
					  title="提示"
					  iconType="warning"
					  footer={[
					    <Button key="submit" type="primary" onClick={this.handleOkRefuseApply}>
					      确认
					    </Button>,
					  ]}
					>
					  <p className="textAlign">
					  		<b>拒绝申请</b>
					  		<span>您拒绝了该用户的加入组织申请，该用户无法成为您所管理的组织的使用者。若您仍然想要将此用户加入您的组织，请重新发起邀请。</span>
						  {/*<span className="CommonTips">您是否确认通过</span>
						  <span className="userName"> {this.state.userName} 的申请</span>*/}
					  </p>
					</Modal>
					<Modal
					  visible={visibleRefuse}
					  title="提示"
					  iconType="warning"
					  onCancel={this.handleCancel}
					  footer={[
					    <Button key="back" onClick={this.handleCancel}>取消</Button>,
					    <Button key="submit" type="primary" onClick={this.handleOkRefuse}>
					      确认拒绝
					    </Button>,
					  ]}
					>
					  <div className="textAlign">
					  		<b>您确定拒绝申请吗？</b>
					  		<span>一旦您确定此拒绝操作，本次申请将作废，若想将该用户加入您的组织，您必须重新邀请该用户。确定拒绝吗？</span>
						  {/*<span className="CommonTips">您是否确认拒绝</span>
						  <span className="userName"> {this.state.userName} 的申请</span>*/}
					  </div>
					</Modal>
					<Modal className="inviteUserPop"
					  visible={visibility}
					  title="邀请用户"
					  onCancel={this.handleCancel}
					  footer={[null]}
					>
					  <div className="invitationBox">
					  	<div className="titleTips"><i>!</i>您可以在“管理我创建的组织”中查看对方申请进度。</div>
					  	<FormItem
						    label="邀请状态"
						    labelCol={{ span: 4 }}
						    wrapperCol={{ span: 18 }}
						>
						    <RadioGroup name="radiogroup" defaultValue={1} onChange={this.onChangeRadio} value={this.state.value}>
					          <Radio value={1}>开放邀请</Radio>
					          <Radio value={2}>关闭邀请</Radio>
					        </RadioGroup>
						</FormItem>
					  	<FormItem
						    label="邀请码"
						    labelCol={{ span: 4 }}
						    wrapperCol={{ span: 18 }}
						>	
							<div className="invitationCode">
								<em className="code">{this.state.code}</em>
								<span className="copyCode" onClick={this.copyCode}>复制邀请码</span>
							</div>
							<p className="copyCodeTips" style={{marginBottom: 0}}>请您记录好邀请码，并发送给被邀请人。被邀请人可在“加入组织”中填写信息并提交加入申请。</p>
						    
						</FormItem>
						{/*<p style={{marginLeft: 50}}>
						    加入组织： {this.state.link}
						    <span className="copyCode" onClick={this.copyLink}>复制“加入组织”链接</span>
						</p>*/}
						<Button key="submit" type="primary" className="inviteCodeBtn" disabled={disabled} onClick={this.InviteCode}>
						  重新生成邀请码
						</Button>
					  </div>
					</Modal>
				</div>
			</div>	
		);
	}
}

export default UserList;
